package com.example.elasticsearch;

import com.example.elasticsearch.entity.Goods;
import com.example.elasticsearch.mapper.GoodsMapper;
import com.example.elasticsearch.mapper.GoodsRepository;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.metrics.ParsedMax;
import org.elasticsearch.search.aggregations.metrics.ParsedMin;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilterBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * 必须添加类描述
 *
 * @author HTJT
 * @date 2023/3/7 15:11
 * @version 1.0
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class Metric {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 案例：分别获取最贵的商品和获取最便宜的商品
     */
    @Test
    public void aggMetric() {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 聚合条件
        queryBuilder.addAggregation(AggregationBuilders.max("maxPrice").field("price"));
        queryBuilder.addAggregation(AggregationBuilders.min("minPrice").field("price"));
        queryBuilder.withSourceFilter(new FetchSourceFilterBuilder().build());
        //查询,获取查询结果
        SearchHits<Goods> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), Goods.class, IndexCoordinates.of("goods"));
        //获取聚合结果
        Aggregations aggregations = searchHits.getAggregations();
        assert aggregations != null;
        //打印聚合结果
        ParsedMax max = aggregations.get("maxPrice");
        System.out.println("最贵的价格：" + max.getValue());
        ParsedMin min = aggregations.get("minPrice");
        System.out.println("最便宜的价格：" + min.getValue());
    }



}
